package algorithm.leetcode;

import java.util.Arrays;

public class LeetCode_1818_minAbsoluteSumDiff {
    public static int minAbsoluteSumDiff(int[] nums1, int[] nums2) {
        final int MOD = 1000000007;
        int length = nums1.length;
        int[] rec = new int[length];
        System.arraycopy(nums1, 0, rec, 0, length);
        Arrays.sort(rec);
        int sum = 0, maxn = 0;
        for (int i = 0; i < length; i++) {
            int diff = Math.abs(nums1[i] - nums2[i]);
            sum = (sum + diff) % MOD;
            int index = binarySearch(rec, nums2[i]);
//            int j = Arrays.binarySearch(rec, nums2[i]);
            if (index < length) {
                maxn = Math.max(maxn, diff - (rec[index] - nums2[i]));
            }
            if (index > 0) {
                maxn = Math.max(maxn, diff - (nums2[i] - rec[index - 1]));
            }
        }
        return (sum - maxn + MOD) % MOD;

    }

    public static int binarySearch(int[] rec, int target) {
        int low = 0, high = rec.length - 1;
        if (rec[high] < target) {
            return high + 1;
        }
        while (low < high) {
            int mid = (high - low) / 2 + low;
            if (rec[mid] < target) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }


    public static void main(String[] args) {
        int[] nums1 = {1, 7, 5};
        int[] nums2 = {2, 3, 5};
        int res = minAbsoluteSumDiff(nums1, nums2);
        System.out.println(res);
    }
}
